<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title">
      <template v-slot:full-button>
        <el-button
          @click="saveAndSubmit()"
          v-if="(!id || isCopy) && $permission('useApplication:saveAndSubmit')"
          :disabled="!canSave"
          >保存并提交</el-button
        >
        <el-button @click="save()" :disabled="!canSave">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                class="not-mongolia"
                :disabled="true"
                placeholder="请选择领入仓库"
                v-model="formInfo.data.depotName"
              >
                <template #append>
                  <el-icon @click="selectDepotStorage"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-deptName>
              <el-input
                v-if="systemConfig.use_application_store_depot_required_strategy === 0"
                class="not-mongolia"
                :disabled="true"
                placeholder="请选择领用部门"
                v-model="formInfo.data.deptName"
              >
                <template #append>
                  <el-icon @click="selectDept"><Search /></el-icon>
                </template>
              </el-input>
              <el-input
                v-if="systemConfig.use_application_store_depot_required_strategy === 1"
                :disabled="true"
                placeholder="请选择领用部门"
                v-model="formInfo.data.deptName"
              />
            </template>
            <template v-slot:form-exportDepotName>
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择领出仓库"
                v-model="formInfo.data.exportDepotName"
              >
                <template #append>
                  <el-icon @click="selectDepotExport"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title div-flex">
          <Tooltip :text="$t('detailInfo')" />
          <modelTips
            :items="modelTipsInfo.items"
            :title="modelTipsInfo.title"
            :brackets="true"
          />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct()"
                >添加产品
              </el-button>
            </template>
            <template v-slot:filter-deleteProduct>
              <el-button :disabled="!canDeleteProduct" @click="deleteProduct"
                >删除产品
              </el-button>
            </template>
            <template v-slot:filter-delNoStockProduct>
              <el-button
                v-if="$permission('useApplicationOrder:delNoStockProduct')"
                :disabled="!canDelNoStockProduct"
                @click="delNoStockProduct"
                >删除无库存产品
              </el-button>
            </template>
            <template v-slot:filter-selectUseTemplate>
              <el-button
                v-if="!id"
                :disabled="!canAddProduct"
                @click="selectUseTemplate"
                >选择模板
              </el-button>
            </template>
          </NewPageFilter>
          <div class="flex_full_item">
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :tabIndex="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item
                    class="margin-bottom"
                    v-if="scope.row.qtyOperateMode !== 3"
                  >
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              @change="
                                changeLarge(
                                  $event,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                              :min="0"
                              :max="99999999"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div>
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="scope.row.unitConvertCoefficient - 1"
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div>
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                  <span v-else>{{ $fn.qtyFormatter(scope.row.qty) }}</span>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!-- 选择产品 -->
    <SelectProductWithStockQty
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      :query="productInfo.query.queryMap"
      :query-params="productInfo.query.queryParams"
      :table-key="productInfo.tableKey"
      :allowUseQtyGreaterStock="productInfo.allowUseQtyGreaterStock"
      :showCheckBox="true"
      :show-price="$permission('useApplication:price')"
      @callback="selectProduct"
    />

    <!-- 选择部门 -->
    <SelectDept
      v-if="deptInfo.visible"
      v-model:showDialog="deptInfo.visible"
      :query="deptInfo.query"
      @callback="selectDeptCallback"
      :checkBox="false"
      :highlightRow="true"
    />
    <!-- 选择领入仓库 -->
    <SelectDepot
      v-if="depotInfo.visible"
      v-model:showDialog="depotInfo.visible"
      @callback="selectStoreDepotCallback"
      :saveEmpty="true"
      :checkBox="false"
      :query="depotInfo.query"
      :highlightRow="true"
    />

    <SelectDepot
      v-if="exportDepotInfo.visible"
      v-model:showDialog="exportDepotInfo.visible"
      @callback="selectExportDepotCallback"
      :saveEmpty="true"
      :checkBox="false"
      :api="exportDepotInfo.api"
      :query="exportDepotInfo.query"
      :highlightRow="true"
    />

    <select-purch-template
      v-if="templateInfo.visible"
      v-model:show-dialog="templateInfo.visible"
      :query="templateInfo.query"
      :api="templateInfo.api"
      :check-box="true"
      :highlight-row="false"
      :tab-index="true"
      @callback="selectTemplateCallback"
    />
  </div>
</template>

<script setup name="useApplicationModify">
import {
  getUseApplication,
  getUseApplicationDetailCustomizeList,
  getUseTemplateDetailAll,
  createUseApplication,
  createUseApplicationAndSave,
  updateUseApplication,
  getUseTemplatePage,
  applicationValidateSubDepot,
} from '@/api/use'
import { getCustomizeSetting } from '@/api/customize'
import {
  postPrintQrCodeScan,
  getProductWithOtherCustomizeList,
  getDepotById,
} from '@/api/core'
import utils from '@/common/js/utils'
import { ElMessageBox } from 'element-plus'
import { getDepotPage } from '@/api/core.js'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const SelectProductWithStockQty = defineAsyncComponent(() =>
  import('@/components/SelectProductWithStockQty/index')
)
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))

const props = defineProps(['visible', 'title', 'id', 'isCopy', 'auditData'])

const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const formRefs = ref([])
const scanApi = postPrintQrCodeScan
const scanFilter = ref({})
const modelTipsInfo = reactive({
  title: '高水位预警',
  items: [
    {
      label: '超过',
      style: { width: '10px', height: '10px', background: '#f7c1c1' },
    },
  ],
})

//表单相关
const formInfo = reactive({
  ref: null,
  supDepotIds: proxy.$store.state.user.userInfo.coreResourcesVO
    ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
        '1'
      ) !== -1 &&
      proxy.$store.state.user.userInfo.coreResourcesVO.isCargoSpaceManage !== 1
      ? proxy.$store.state.user.userInfo.coreResourcesVO.supDepotIds || []
      : ''
    : '',
  data: {
    applicationUserName: proxy.$store.state.user.userInfo.user
      ? proxy.$store.state.user.userInfo.user.name
      : '',
    deptName: '',
    deptId: '',
    exportDeptName: '',
    exportDeptId: '',
    depotName: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1 &&
        proxy.$store.state.user.userInfo.coreResourcesVO.isCargoSpaceManage !==
          1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
        : ''
      : '',
    depotId: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
          '1'
        ) !== -1 &&
        proxy.$store.state.user.userInfo.coreResourcesVO.isCargoSpaceManage !==
          1
        ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
        : ''
      : '',
    exportDepotName: '',
    exportDepotId: '',
  },
  fieldList: [
    {
      label: '领用人',
      value: 'applicationUserName',
      type: 'input',
      disabled: true,
    },
    {
      label: '领入仓库',
      value: 'depotName',
      type: 'slot',
    },
    {
      label: '领用部门',
      value: 'deptName',
      type: 'slot',
    },
    {
      label: '领出仓库',
      value: 'exportDepotName',
      type: 'slot',
    },
    {
      label: '领出部门',
      value: 'exportDeptName',
      type: 'input',
      disabled: true,
    },
    // {
    //   label: '是否寄售业务',
    //   value: 'isConsignBusinessValue',
    //   type: 'input',
    //   disabled: true,
    //   show:
    //     props.id &&
    //     proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    // },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    depotName: [
      {
        required:
          systemConfig.value.use_application_store_depot_required_strategy === 1
            ? true
            : false,
        message: '请选择领入仓库',
        trigger: 'change',
      },
    ],
    exportDepotName: [
      {
        required:
          systemConfig.value.use_application_export_depot_required_strategy === 1
            ? true
            : false,
        message: '请选择出库仓库',
        trigger: 'change',
      },
    ],
    deptName: [{ required: true, message: '请输入领用部门', trigger: 'blur' }],
    exportDeptName: [
      {
        required:
          systemConfig.value.use_application_export_depot_required_strategy === 1
            ? true
            : false,
        message: '请输入领出部门',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
  },
  list: [
    {
      type: 'slot',
      value: 'addProduct',
    },
    {
      type: 'slot',
      value: 'deleteProduct',
    },
    {
      type: 'slot',
      value: 'delNoStockProduct',
    },
    {
      type: 'slot',
      value: 'selectUseTemplate',
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    {
      value: 'qty',
      formatter: proxy.$fn.qtyFormatter,
    },
    { value: 'price', show: 'false' },
    {
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: deleteProduct,
        show: true,
      },
    ],
  },
})
//选择产品相关
let productInfo = reactive({
  visible: false,
  allowUseQtyGreaterStock: computed(() => {
    return systemConfig.value.allow_use_qty_greater_stock
  }),
  tableKey:
    'useApplicationOrderModifyProductWithOther-com.slip.spd.entity.vo.core.CoreProductWithOtherVO',
  query: {
    queryMap: {
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: 1,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: '',
      },
      isConsignment: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      userDeptId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {
      exportDepotId: '',
      storeDepotId: proxy.$store.state.user.userInfo.coreResourcesVO
        ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
            '1'
          ) !== -1 &&
          proxy.$store.state.user.userInfo.coreResourcesVO
            .isCargoSpaceManage !== 1
          ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
          : ''
        : '',
      checkDeptProduct: 1,
      isDeptProduct: 1,
      deptId: proxy.$store.state.user.userInfo.dept
        ? proxy.$store.state.user.userInfo.dept.id
        : '',
      forbidden: 1,
    },
  },
})
const userInfo = reactive({
  visible: false,
})
const depotInfo = reactive({
  visible: false,
  depotType: '',
  query: {
    idNot: '',
    useTypeId: '1',
    status: '1',
  },
})
const exportDepotInfo = reactive({
  visible: false,
  depotType: '',
  api: getDepotPage,
  query: {
    useTypeId: '1',
    status: '1',
    idMult: '',
    idNot: '',
  },
})
const deptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
    status: '1',
  },
})
const templateInfo = reactive({
  visible: false,
  api: getUseTemplatePage,
  query: {
    deptId: '',
  },
})

watch(
  () => tableInfo.data,
  () => {
    tableInfo.data.forEach((row) => {
      let smallUnitQty = parseFloat(row.smallUnitQty || 0)
      let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
      let largeUnitQty = parseFloat(row.largeUnitQty || 0)
      let calcQty = proxy.$fn.accAdd(
        proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
        smallUnitQty
      )
      let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
      row['calcQty'] = calcQty
      row['qty'] = qty
      row.sumAmount = proxy.$fn.accMul(
        proxy.$fn.accAdd(
          proxy.$fn.accDiv(smallUnitQty, unitConvertCoefficient),
          largeUnitQty
        ),
        parseFloat(row.price)
      )
      row.productionDate =
        row.productionDate === '1900-01-01' ? undefined : row.productionDate
    })
  },
  {
    deep: true,
  }
)
const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.data.length
})
const canDeleteProduct = computed(() => {
  return tableInfo.selections.length
})
const canDelNoStockProduct = computed(() => {
  let arr = tableInfo.data.filter((row) => row.exportStockQty === 0)
  return tableInfo.data.length && arr.length
})
const canAddProduct = computed(() => {
  return formInfo.data.deptName
})

let obj = {
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    // type: 'slot',
    hidden: true,
  },
  qty: {
    label: '数量',
    value: 'qty',
    type: 'slot',
    minWidth: '250px',
    hidden: true,
  },
  storeStockQty: {
    label: '领入仓库可用数量',
    value: 'storeStockQty',
    hidden: true,
    type: 'column',
    formatter: utils.qtyFormatter,
  },
  exportStockQty: {
    label: '领出仓库可用数量',
    value: 'exportStockQty',
    hidden: true,
    type: 'column',
    formatter: utils.qtyFormatter,
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useApplication:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useApplication:price'),
    hidden: true,
  },
  productionDate: {
    label: '生成日期',
    value: 'productionDate',
    type: 'slot',
    minWidth: '160px',
    hidden: true,
  },
  validityDate: {
    label: '失效日期',
    value: 'validityDate',
    minWidth: '160px',
    type: 'slot',
    hidden: true,
  },
  batchNumber: {
    label: '批号',
    value: 'batchNumber',
    type: 'slot',
    hidden: true,
  },
  defaultSupplierName: {
    label: '默认供应商',
    value: 'defaultSupplierName',
    type: 'column',
    hidden: true,
  },
  defaultSupplierCode: {
    label: '默认供应商编码',
    value: 'defaultSupplierCode',
    type: 'column',
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useApplication:price'),
    hidden: true,
  },
  preExportQty: {
    label: '预出库数量',
    value: 'preExportQty',
    type: 'column',
    show: false,
    hidden: true,
  },
  exportQty: {
    label: '出库数量',
    value: 'exportQty',
    type: 'column',
    show: false,
    hidden: true,
  },
  storeQty: {
    label: '入库数量',
    value: 'storeQty',
    type: 'column',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
if (!props.id) {
  formInfo.fieldList = formInfo.fieldList.filter(
    (item) => item.value !== 'orderNo'
  )
}

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  })
  formInfo.data.depotId = proxy.$store.state.user.userInfo.coreResourcesVO
    ? proxy.$store.state.user.userInfo.coreResourcesVO.useTypeId.indexOf(
        '1'
      ) !== -1 &&
      proxy.$store.state.user.userInfo.coreResourcesVO.isCargoSpaceManage !== 1
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
      : ''
    : ''
  if (props.auditData && props.auditData.id) {
    //补充库存
    formInfo.data.depotName = props.auditData.exportDepotName
    formInfo.data.depotId = props.auditData.exportDepotId
    formInfo.data.deptName = props.auditData.exportDeptName
    formInfo.data.deptId = props.auditData.exportDeptId
    productInfo.query.queryParams.storeDepotId = formInfo.data.depotId
  } else {
    getDepot()
  }
  //领出仓库必填时自动带出领出仓库
  if (systemConfig.value.use_application_export_depot_required_strategy === 1) {
    getExportDepotId(formInfo.data.depotId)
  }
})
function getDepot() {
  if (formInfo.data.depotId && formInfo.data.depotId !== -2) {
    getDepotById(formInfo.data.depotId).then((res) => {
      if (res && res.success) {
        formInfo.data.deptName = res.data.deptName
        formInfo.data.deptId = res.data.deptId
      }
    })
  }
}
function changeLarge(e, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function generateProductKey(products) {
  return products.map((item) => {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate
    item._id = key
    return item
  })
}
function getList() {
  getUseApplicationDetailCustomizeList(filterInfo.query).then((res) => {
    if (res && res.success) {
      if (props.isCopy) {
        res.data.forEach((val) => {
          val.price = val.defaultSupplierPrice
        })
        formInfo.data.id = null
      }
      const prodeuctsData = generateProductKey(res.data)
      tableInfo.data = prodeuctsData
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'useApplicationOrderModify-com.slip.spd.entity.vo.use.UseApplicationOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      filterInfo.query.customizeUserVO = data
      if (props.id) {
        getMain()
      }
    }
  })
}
function getMain() {
  getUseApplication(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
      scanFilter.value.deptId = resp.data.deptId
      productInfo.query.queryParams.exportDepotId = resp.data.exportDepotId
      productInfo.query.queryParams.storeDepotId = resp.data.depotId
      productInfo.query.queryParams.deptId = formInfo.data.deptId
      productInfo.query.queryParams.forbidden = 1
      formInfo.supDepotIds = resp.data.supDepotIds || []
    }
  })
  filterInfo.query.queryMap.orderId.value = props.id ////
  getList()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = data
      break
  }
}
function selectUseTemplate() {
  applicationValidateSubDepot(formInfo.data).then((res) => {
    if (res && res.success) {
      //根据策略过滤
      if (systemConfig.value.use_application_template_strategy === 1) {
        // 领入仓库所属部门
        templateInfo.query.deptId = formInfo.data.deptId
      } else {
        // 领用人所在部门
        templateInfo.query.deptId = proxy.$store.state.user.userInfo.dept
          ? proxy.$store.state.user.userInfo.dept.id
          : ''
      }
      templateInfo.visible = true
    }
  })
}
function selectTemplateCallback(data) {
  if (data) {
    let ids = data.map((row) => row.id)
    let orderIds = String(ids)
    const params = {
      orderIdIn: orderIds,
      exportDepotId: productInfo.query.queryParams.exportDepotId,
      storeDepotId: productInfo.query.queryParams.storeDepotId,
    }
    getUseTemplateDetailAll(params).then((resp) => {
      if (resp && resp.success) {
        resp.data = resp.data.filter((item) => {
          return tableInfo.data.every((el) => el.productId !== item.productId)
        })
        tableInfo.data = resp.data.concat(tableInfo.data)
        tableInfo.data.forEach(function (item) {
          item.price = item.defaultSupplierPrice
          item.supplierName = item.defaultSupplierName
        })
      }
    })
  }
}
//删除无库存产品
function delNoStockProduct() {
  if (tableInfo.data.length > 0) {
    tableInfo.data = tableInfo.data.filter((row) => row.exportStockQty !== 0)
  }
}
//删除产品
function deleteProduct(data = undefined) {
  if (tableInfo.selections.length > 0) {
    tableInfo.data = tableInfo.data.filter(
      (row) => !tableInfo.selections.includes(row)
    )
  } else if (data && data.id) {
    tableInfo.data = tableInfo.data.filter((row) => data !== row)
  }
}
//添加产品
function addProduct() {
  applicationValidateSubDepot(formInfo.data).then((res) => {
    if (res && res.success) {
      const productIds = tableInfo.data.map((item) => item.productId)
      productInfo.query.queryMap.id.value = productIds.toString()
      if (props.id) {
        productInfo.query.queryMap.isConsignment.value =
          formInfo.data.isConsignBusiness
      }
      productInfo.query.queryParams.deptId = formInfo.data.deptId
      if (systemConfig.value.use_application_dept_product_strategy === 1) {
        // 领用入库部门
        productInfo.query.queryParams.userDeptId = formInfo.data.deptId
      } else {
        // 申请人所在部门
        productInfo.query.queryParams.userDeptId = proxy.$store.state.user
          .userInfo.dept
          ? proxy.$store.state.user.userInfo.dept.id
          : ''
      }
      productInfo.visible = true
    }
  })
}
//选择产品
function selectProduct(rows) {
  if (rows) {
    rows = generateProductKey(rows)
    const data = rows.map(function (item) {
      return {
        ...item,
        productId: item.id,
        price: item.price,
        defaultSupplierPrice: item.price,
        defaultSupplierId: item.supplierId,
        defaultSupplierName: item.supplierName,
        defaultSupplierCode: item.supplierCode,
        storeStockQty: item.storeStockQty || 0,
        exportStockQty: item.exportStockQty || 0,
      }
    })
    tableInfo.data = data.concat(tableInfo.data)
  }
}
function tableRowClassName({ row }) {
  if (row.hasOwnProperty('depotStockHighQty')) {
    let qty = proxy.$fn.accDiv(
      proxy.$fn.accAdd(row.calcQty || 0, row.depotStockCalcQty),
      row.unitConvertCoefficient
    )
    if (qty > row.depotStockHighQty) {
      return 'warning-row'
    } else {
      return ''
    }
  }
  return ''
}
//选择领出仓库
function selectDepotExport() {
  // if (!formInfo.data.depotId) {
  //   proxy
  //     .$confirm('请选择领入仓库', '提示', {
  //       confirmButtonText: '确定',
  //       cancelButtonText: '取消',
  //       type: 'warning',
  //     })
  //     .then(() => {
  //       selectDepotStorage()
  //     })
  //   return
  // }
  exportDepotInfo.depotType = 'export'
  exportDepotInfo.query.idMult = formInfo.supDepotIds.length
    ? formInfo.supDepotIds.toString()
    : ''
  if (!formInfo.data.depotId) {
    exportDepotInfo.query.idNot = formInfo.data.exportDepotId
  } else {
    exportDepotInfo.query.idNot =
      formInfo.data.depotId +
      (formInfo.data.exportDepotId ? ',' + formInfo.data.exportDepotId : '')
  }
  exportDepotInfo.visible = true
}
//选择领入仓库
function selectDepotStorage() {
  depotInfo.depotType = 'storage'
  depotInfo.query.depotAuth = 'id'
  depotInfo.visible = true
  depotInfo.query.subDepotId = ''
  depotInfo.query.isCargoSpaceManage = 0
}

function selectStoreDepotCallback(row) {
  if (row && row.id) {
    if (formInfo.data.depotId !== row.id) {
      tableInfo.data = []
      formInfo.data.depotId = row.id
      formInfo.data.depotName = row.name
      formInfo.data.deptName = row.deptName
      formInfo.data.deptId = row.deptId
      formInfo.supDepotIds = row.supDepotIds
      formInfo.data.exportDepotName = ''
      formInfo.data.exportDepotId = ''
      formInfo.data.exportDeptName = ''
      formInfo.data.exportDeptId = ''
    }
    productInfo.query.queryParams.storeDepotId = row.id
    //领出仓库必填时自动带出领出仓库
    if (
      systemConfig.value.use_application_export_depot_required_strategy === 1
    ) {
      getExportDepotId(formInfo.data.depotId)
    }
  } else {
    tableInfo.data = []
    formInfo.data.depotId = ''
    formInfo.data.depotName = ''
    formInfo.data.deptName = ''
    formInfo.data.deptId = ''
    formInfo.data.exportDepotName = ''
    formInfo.data.exportDepotId = ''
    formInfo.data.exportDeptName = ''
    formInfo.data.exportDeptId = ''
    productInfo.query.queryParams.storeDepotId = ''
    formInfo.supDepotIds = []
  }
}
function selectExportDepotCallback(row) {
  if (row && row.id) {
    if (formInfo.data.exportDepotId !== row.id) {
      tableInfo.data = []
      formInfo.data.exportDepotId = row.id
      formInfo.data.exportDepotName = row.name
      formInfo.data.exportDeptName = row.deptName ? row.deptName : ''
      formInfo.data.exportDeptId = row.deptId ? row.deptId : ''
    }
    productInfo.query.queryParams.exportDepotId = row.id
  } else {
    tableInfo.data = []
    formInfo.data.exportDepotId = ''
    formInfo.data.exportDepotName = ''
    formInfo.data.exportDeptName = ''
    formInfo.data.exportDeptId = ''
    productInfo.query.queryParams.exportDepotId = ''
  }
}
function selectDept() {
  deptInfo.visible = true
  deptInfo.query.idNot = formInfo.data.deptId
}
function getExportDepotId(depotId) {
  //自动带出可领仓库第一个
  let exportDepotQuery = {}
  exportDepotQuery.subDepotId = depotId
  exportDepotQuery.searchType = 'depot'
  exportDepotQuery.status = '1'
  exportDepotQuery.useTypeId = '1'
  exportDepotQuery.sort = 'create_time desc'
  getDepotPage(exportDepotQuery).then((res) => {
    if (res.success && res.data && res.data.length > 0) {
      for (let i = 0; i < res.data.length; i++) {
        if (!res.data[i].lock) {
          formInfo.data.exportDepotId = res.data[i].id
          formInfo.data.exportDepotName = res.data[i].name
          formInfo.data.exportDeptName = res.data[i].deptName
            ? res.data[i].deptName
            : ''
          formInfo.data.exportDeptId = res.data[i].deptId
            ? res.data[i].deptId
            : ''
          productInfo.query.queryParams.exportDepotId = res.data[i].id
          break
        }
      }
      if (props.auditData && props.auditData.id) {
        getProductCustomize()
      }
    }
  })
}
function selectDeptCallback(row) {
  if (row) {
    formInfo.data.deptName = row.name
    formInfo.data.deptId = row.id
    // formInfo.data.depotName = formInfo.data.depotName
    //   ? formInfo.data.depotName
    //   : row.coreResourcesVO
    //   ? row.coreResourcesVO.resourceName
    //   : ''
    // formInfo.data.depotId = formInfo.data.depotId
    //   ? formInfo.data.depotId
    //   : row.coreResourcesVO
    //   ? row.coreResourcesVO.resourceId
    //   : ''
    formInfo.data.depotName = ''
    formInfo.data.depotId = ''
    productInfo.query.queryParams.storeDepotId = ''
    tableInfo.data = []
  }
}
function selectSourceDeptCallback(row) {
  if (row) {
    formInfo['data'] = {
      ...formInfo.data,
      exportDeptName: row.name,
      exportDeptId: row.id,
    }
  }
}
//保存
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let details = tableInfo.data.filter((row) => row.productId && row.qty)
    if (!details.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '请添加有效的产品',
      })
      return
    }

    details = details.map((detail) => {
      if (!detail.exportStockQty) {
        detail.exportStockQty = 0
      }
      return detail
    })

    const errorStockProduct = details
      .filter((detail) => detail.qty > detail.exportStockQty)
      .map((detail) => detail.commonName)
    if (errorStockProduct.length) {
      if (systemConfig.value.allow_use_qty_greater_stock === 0) {
        proxy.$message({
          duration: 3500,
          type: 'error',
          showClose: true,
          message: `产品【${errorStockProduct}】申请数量不能大于领出仓库可用数量`,
        })
        return
      } else {
        ElMessageBox.confirm(
          `产品【${errorStockProduct}】申请数量大于领出仓库可用数量`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            let commonNameList = details
              .filter((row) => {
                let qty = proxy.$fn.accDiv(
                  proxy.$fn.accAdd(row.calcQty || 0, row.depotStockCalcQty),
                  row.unitConvertCoefficient
                )
                return qty > row.depotStockHighQty
              })
              .map((detail) => detail.commonName)
            if (commonNameList.length) {
              ElMessageBox.confirm(
                `产品【${commonNameList}】申请数量加领入仓库总数大于仓库高水位`,
                '提示',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                }
              ).then(() => {
                saveData(details, isSaveAndSubmit)
              })
            } else {
              saveData(details, isSaveAndSubmit)
            }
          })
          .catch(() => {})
      }
    } else {
      let commonNameList = details
        .filter((row) => {
          console.log(344444444)
          console.log(row)
          let qty = proxy.$fn.accDiv(
            proxy.$fn.accAdd(row.calcQty || 0, row.depotStockCalcQty),
            row.unitConvertCoefficient
          )
          console.log(33333333)
          console.log(qty)
          return qty > row.depotStockHighQty
        })
        .map((detail) => detail.commonName)
      if (commonNameList.length) {
        ElMessageBox.confirm(
          `产品【${commonNameList}】申请数量加领入仓库总数大于仓库高水位`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          saveData(details, isSaveAndSubmit)
        })
      } else {
        saveData(details, isSaveAndSubmit)
      }
      //const data = formInfo.data;
      //data.details = proxy.$fn.filterBlacklist(details);
      //data.type = "use";
      //const api = data.id ? updateUseApplication : createUseApplication;
      //api(data).then(resp => {
      //  if (resp && resp.success) {
      //    showDialog.value = false;
      //    emit("returnModify");
      //  }
      //});
    }
  })
}
function saveData(details, isSaveAndSubmit) {
  const data = formInfo.data
  data.details = proxy.$fn.filterBlacklist(details)
  data.type = 'use'
  const api = data.id
    ? updateUseApplication
    : isSaveAndSubmit === true
    ? createUseApplicationAndSave
    : createUseApplication
  api(data).then((resp) => {
    if (resp && resp.success) {
      showDialog.value = false
      emit('returnModify')
    }
  })
}
function getProductCustomize() {
  let filterInfo = {
    query: {
      curPage: 1,
      page: true,
      pageSize: 9999,
      customizeUserVO: {},
      queryMap: {
        status: {
          queryType: 'IN',
          queryCategory: 'AND',
          value: 1,
        },
        type: {
          asTbName: 'core_product_new',
          columnName: 'type',
          queryResource: 0,
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: 0,
        },
      },
    },
  }
  filterInfo.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  })
  let param = {
    tableKey: productInfo.tableKey,
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.searchList = searchInfo.searchList
      filterInfo.query.customizeUserVO = data
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,

        ...filterInfo.query.queryMap,
      }
      getProductList(filterInfo)
    }
  })
}
function getProductList(filterInfo) {
  let tableIds = props.auditData.details
    .map((item) => item.productId)
    .toString()
  filterInfo.query.queryParams = {
    exportDepotId: formInfo.data.exportDepotId,
    storeDepotId: formInfo.data.depotId,
    checkDeptProduct: 1,
    deptId: formInfo.data.deptId,
    productIds: tableIds,
  }
  getProductWithOtherCustomizeList(filterInfo.query).then((res) => {
    if (res && res.data) {
      let data = res.data
      tableInfo.data = props.auditData.details
      tableInfo.data = tableInfo.data.map((item) => {
        data.forEach((el) => {
          if (item.productId === el.id) {
            item.exportStockQty = el.exportStockQty
            item.storeStockQty = el.storeStockQty
          }
        })
        return item
      })
    }
  })
}
</script>

<style scoped></style>
